<template>
  <BaseMainSlot :show-tab="true" :show-search-box="false">
    <template v-slot:search-box>
      
    </template>
    <template v-slot:btn-box>
      <ActionBar
        :page-no="39"
        :add-active="addActive"
        :del-active="delActive"
        :has-edit="false"
        :has-save="false"
        :has-cancel="false"
        @add="add"
        @del="del"
      />
    </template>
    <template v-slot:table-box>
      <el-table
        ref="tableData"
        v-loading="loading"
        highlight-current-row
        :data="tableData"
        stripe
        border
        height="92%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column
          v-for="item, index in formDatalists"
          :key="index"
          :prop="item.porp"
          :label="item.name"
          min-width="200"
          :column-key="`${item.porp}`"
        >
          <template
            v-if="scope.row[`addressNo`] !== undefined"
            slot-scope="scope"
          >
            <span
              v-if="item.porp === 'isFreecust'"
            >{{ scope.row[item.porp] ? '是':'否' }}</span>
            <span
              v-else-if="item.porp === 'enableStatus'"
            >{{ scope.row[item.porp] ? '是':'否' }}</span>
            <span v-else>{{ scope.row[item.porp] || '——' }}</span>
          </template>
        </el-table-column>
        <el-table-column min-width="160" label="操作" fixed="right">
          <template v-if="scope.row.addressNo" slot-scope="scope">
            <el-button
              v-if="judgePermission(39, 'edit')"
              class="text-btn-cursor"
              type="text"
              size="small"
              @click="edit(scope.row)"
            >
              <i class="el-icon-edit-outline"></i> 修改
            </el-button>
            <el-button
              v-if="judgePermission(39, 'delete')"
              class="text-btn-cursor cursor-delete"
              type="text"
              size="small"
              @click="handleDelete(scope.row.addressNo)"
            >
              <i class="el-icon-delete"></i> 删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <Pagination
        :page-size="pageSize"
        :current-page="currentPage"
        :total-size="totalSize"
        @changePageSize="changePageSize"
        @changeCurrentPage="changeCurrentPage"
      />
    </template>
    <template v-slot:dialog>
      <el-dialog
        :title="titleText"
        :visible.sync="dialogFormVisible"
        @close="cancel('formData')"
      >
        <el-form
          ref="formData"
          label-position="left"
          :model="formData"
          :rules="rules"
          class="el-form"
        >
          <el-form-item label="国家 :" prop="country" class="w50p">
            <el-input v-model="formData.country" placeholder="请选择" clearable />
          </el-form-item>
          <el-form-item
            label="省份 :"
            prop="provinceObj.districtName"
            class="w50p"
            :rules="[
              { required: true, message: '省份不能为空', trigger: 'blur' },
            ]"
          >
            <el-select
              v-model="formData.provinceObj"
              value-key="districtName"
              clearable
              filterable
              default-first-option
              placeholder="请选择省份"
              @change="getFlowRegion($event,1)"
            >
              <el-option
                v-for="(item,index) in provinceList"
                :key="index"
                :label="item.districtName"
                :value="{...item}"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="城市 :"
            prop="cityObj.districtName"
            class="w50p"
            :rules="[
              { required: true, message: '城市不能为空', trigger: 'blur' },
            ]"
          >
            <el-select
              v-model="formData.cityObj"
              value-key="districtName"
              clearable
              filterable
              default-first-option
              placeholder="请选择城市"
              @change="getFlowRegion($event,2)"
            >
              <el-option
                v-for="(item,index) in cityList"
                :key="index"
                :label="item.districtName"
                :value="{...item}"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="县区 :" prop="vsection" class="w50p">
            <el-select
              v-model="formData.vsection"
              clearable
              filterable
              default-first-option
              placeholder="请选择县区"
            >
              <el-option
                v-for="(item,index) in vsectionList"
                :key="index"
                :label="item.districtName"
                :value="item.districtName"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="地址详址 :" prop="detailinfo" class="w50p">
            <el-input
              v-model="formData.detailinfo"
              type="textarea"
              placeholder="请输入详细地址"
              clearable
            />
          </el-form-item>
          <el-form-item label="邮政编码 :" prop="postcode" class="w50p">
            <el-input
              v-model="formData.postcode"
              placeholder="请输入邮政编码"
              clearable
            />
          </el-form-item>
          <el-form-item label="备注 :" class="w50p">
            <el-input
              v-model="formData.remarks"
              type="textarea"
              :rows="2"
              placeholder="请输入备注"
              clearable
            />
          </el-form-item>
        </el-form>
        <div v-if="nowChanceStau !== ''" slot="footer" class="dialog-footer">
          <el-button class="zh-button-one" @click="cancel('formData')">取 消</el-button>
          <el-button
            class="zh-button-two"
            type="primary"
            @click="save('formData')"
          >保 存</el-button>
        </div>
      </el-dialog>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import Pagination from "@/components/Pagination";
import SearchBox from "@/components/SearchBox";
import BaseMainSlot from "@/components/BaseMainSlot/newBaseMainSlot";
import { mymixin } from "@/utils/mixins";
import addressApi from "@/api/livestock-manage/inventory/address/addressManage";
import regionApi from "@/api/livestock-manage/inventory/address/region";
import { mapGetters } from "vuex";
export default {
  name: "SheepInformation",
  components: { ActionBar, Pagination, BaseMainSlot, SearchBox },
  mixins: [mymixin],
  data() {
    // selectValue 用于传递select的编号
    // isCheck 是否需要单独校验 required是否需要校验 notSearch 是否需要表头搜索
    return {
      selectedStaffList: [],
      provinceList: [],
      cityList: [],
      vsectionList: [],
      districtCode: "",
      formDatalists: [
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "country",
          typeObj: {},
          name: "国家",
          required: true,
          notSearch: true
        },
        {
          type: "Select",
          porp: "province",
          selectValue: "districtCode",
          typeObj: {},
          name: "省份",
          required: true,
          notSearch: true
        },
        {
          type: "Select",
          porp: "city",
          selectValue: "districtCode",
          typeObj: {},
          name: "城市",
          required: true,
          notSearch: true
        },
        {
          type: "Select",
          porp: "vsection",
          selectValue: "districtCode",
          typeObj: {},
          name: "县区",
          required: true,
          notSearch: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "detailinfo",
          typeObj: {},
          name: "详细地址",
          required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "postcode",
          typeObj: {},
          name: "邮政编码"
          // required: true
        },
        {
          type: "input", // input Select Checkbox TimePicker
          porp: "remarks",
          typeObj: {},
          name: "备注",
          // required: true,
          notSearch: true
        }
      ],
      rules: {
        country: [{ required: true, message: "国家不能为空", trigger: "blur" }],
        vsection: [
          { required: true, message: "县区不能为空", trigger: "blur" }
        ],
        detailinfo: [
          { required: true, message: "详细地址不能为空", trigger: "blur" }
        ]
      }
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  created() {
    this.search();
    this.getProvince();
  },
  methods: {
    getFlowRegion(e, a) {
      regionApi.queryAddressByParent(e.districtCode).then(res => {
        if (res.code === 1) {
          if (a === 1) {
            this.cityList = res.data;
            this.$set(this.formData, "city", "");
            this.$set(this.formData, "vsection", "");
            this.formData.province = e.districtName;
          } else if (a === 2) {
            this.vsectionList = res.data;
            this.$set(this.formData, "vsection", "");
            this.formData.city = e.districtName;
          }
        }
      });
    },
    // 获取省份
    getProvince() {
      regionApi.queryProvinceList().then(res => {
        if (res.code === 1) {
          this.provinceList = res.data;
          this.$set(this.formDatalists[1], "typeObj", {
            list: res.data,
            listName: ["districtName", "districtCode"]
          });
        }
      });
    },
    getTableDataList() {
      this.loading = true;
      let params = {
        page: this.currentPage,
        size: this.pageSize,
        entity: { ...this.searchObj }
      };
      addressApi.pageQuery(params).then(res => {
        this.loading = false;
        let data = res.data;
        if (data) {
          this.totalSize = data.totalElements;
          this.tableData = data.content;
          this.addblankmet();
          this.resetActionBar();
        }
      });
    },
    handleSelectionChange(list) {
      this.selectedStaffList = [];
      this.selectedStaffList = list.map(item => item.addressNo);
      if (this.selectedStaffList.length > 0) this.delActive = true;
      else this.delActive = false;
    },
    delmessage() {
      addressApi
        .numberBatchDel({ noList: this.selectedStaffList })
        .then(res => {
          if (res.code === 1) {
            this.$message.success(res.msg);
            this.search();
          } else {
            this.$message.warning(res.msg || "删除失败");
          }
        });
    },
    handleDelete(val) {
      this.$confirm("此操作将永久删除该条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "myClass"
      })
        .then(() => {
          // console.log(12);
          addressApi.numberDel(val).then(res => {
            if (res.code === 1) {
              this.$message.success(res.msg);
              this.search();
            } else {
              this.$message.warning(res.msg || "删除失败");
            }
          });
        })
        .catch(() => {});
    },
    add() {
      this.formData = { country: "中国", provinceObj: {}, cityObj: {} };
      this.nowChanceStau = "add";
      this.titleText = "添加地址簿";
      this.addActive = false;
      this.delActive = false;
      this.dialogFormVisible = true;
    },
    edit(row) {
      this.formData = { ...row };
      regionApi
        .queryByCondition({ districtName: row.province, level: 1 })
        .then(res => {
          if (res.code === 1) {
            this.$set(this.formData, "provinceObj", ...res.data);
            regionApi.queryAddressByParent(res.data[0].districtCode).then(res => {
              if (res.code === 1) {
                this.cityList = res.data;
              }
            });
          }
        });
      regionApi
        .queryByCondition({ districtName: row.city, level: 2 })
        .then(res => {
          if (res.code === 1) {
            this.$set(this.formData, "cityObj", ...res.data);
            regionApi.queryAddressByParent(res.data[0].districtCode).then(res => {
              if (res.code === 1) {
                this.vsectionList = res.data;
              }
            });
          }
        });
      this.nowChanceStau = "edit";
      this.titleText = "修改地址簿";
      this.dialogFormVisible = true;
      this.addActive = true;
      this.delActive = false;
    },
    save(formData) {
      this.$refs[formData].validate(valid => {
        if (valid) {
          if (this.nowChanceStau === "edit") {
            addressApi.edit(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "修改成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "修改失败！");
              }
            });
          } else if (this.nowChanceStau === "add") {
            addressApi.add(this.formData).then(res => {
              if (res.code === 1) {
                this.$message.success(res.msg || "新增成功！");
                this.dialogFormVisible = false;
                this.search();
                this.$refs[formData].resetFields();
              } else {
                this.$message.error(res.msg || "新增失败！");
              }
            });
          }
        } else {
          return false;
        }
      });
    }
  }
};
</script>
<style scoped lang="scss">
::v-deep
  .el-dialog__wrapper
  .el-dialog
  .el-dialog__body
  .el-form
  .el-form-item
  .el-form-item__label {
  min-width: 155px;
}
</style>
